package com.infra.server.config;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.infra.server.utils.ConstantUtil;
import com.nimbusds.jose.JWSObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取登录用户信息
 *
 * @author 13764
 */
@Slf4j
@Component
public class LoginUserHolder {

    /**
     * 获取当前登录用户信息
     */
    public JSONObject getCurrentUser() {
        //从Header中获取用户信息
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String userStr = request.getHeader(ConstantUtil.USER_INFO);
        return JSONObject.parseObject(userStr);
    }

    public JSONObject getCurrentUser(String token) {
        //从token中解析用户信息并设置到Header中去
        String realToken = token.replace(ConstantUtil.AUTH_TOKEN_BEARER, "");
        JWSObject jwsObject = null;
        String userStr = "";
        try {
            jwsObject = JWSObject.parse(realToken);
            userStr = jwsObject.getPayload().toString();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return JSONObject.parseObject(userStr);
    }


    /**
     * 判断当前登录用户是否是管理员
     */
    public boolean isAdmin() {
        JSONArray roles = getCurrentUser().getJSONArray("authorities");
        return ObjectUtil.isNotEmpty(roles) && roles.contains(ConstantUtil.ADMINISTRATOR_ROLE);
    }
}
